import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index.js'
import router from '@/router/index.js'
const request = axios.create({
  baseURL: '/api'
  //  'http://ihrm.itheima.net/prod-api'
  // 'http://ihrm-java.itheima.net/api'
})

// 请求拦截器
request.interceptors.request.use(config => {
  // 统一携带token发送、
  if (store.state.user.token) {
    config.headers.Authorization = 'Bearer ' + store.state.user.token
  }
  return config
}, error => {
// Do something with request error
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(response => {
// Do something before response is sent
  const { data: { data, success, message }} = response
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  if (err && err.response && err.response.status === 401) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  Message.error('服务器异常')
  return Promise.reject(err)
})
export default request
